import {
	msg,
	connect,
	prompt
} from "./api.js";

export class Http {
	constructor({
		baseURL = '/school',
		upURL = "/api/v1/upload/add",
		imgUrl = '/school',
		headers = {},
		errorCode = null,
		baseData = {},
		getBaseData = {},
		postBaseData = {},
		$store = {}
	} = {}) {
		Object.assign(this, {
			baseURL,
			imgUrl,
			upURL,
			headers,
			errorCode,
			baseData,
			getBaseData,
			postBaseData,
			$store
		});
	}
	//错误码拦截
	async error(res) {
		if(!res) return new Promise((r, reject) => {
			reject("什么都没有？");
		});
		//没有错误码 说明成功 直接返回
		if(!res.code) return res;
		//错误码 拦截
		switch (res.code - 0) {
			case 200:
			case 111005: //用户未绑定
				return res;
			case 111006: //token失效
				return this.$store.dispatch('logout').then(res => {
					return this.$store.dispatch('login');
				});
		}
		prompt("错误", JSON.stringify(res), !1);
		return new Promise((r, reject) => {
			reject(res);
		});
	}
	//请求
	request(url, data = {}, method) {
		return uni.request({
			method,
			header: this.headers,
			url: connect(this.baseURL, url),
			data: {
				...this.baseData,
				...data
			}
		}).then(res => res[1] || {}).then(res => res.data || {}).then(typeof this.errorCode === 'function' ? this.errorCode :
			this.error);
	}
	//get请求
	get(url, data = {}) {
		return this.request(url, {
			...data,
			...this.getBaseData
		}, "GET");
	}
	//post请求
	post(url, data = {}) {
		return this.request(url, {
			...data,
			...this.postBaseData
		}, "POST");
	}
	//put
	put(url, data = {}) {
		return this.request(url, data, "PUT");
	}
	//Delete
	delete(url, data = {}) {
		return this.request(url, data, "DELETE");
	}
	//上传
	up(filePath, formData = {}, onProgressUpdate = e => {}, uploadTask = e => {}) {
		const { ...header
		} = this.headers;
		delete header['Content-Type'];
		delete header['ContentType'];
		return new Promise(r => {
			let Task = uni.uploadFile({
				url: connect(this.baseURL, this.upURL),
				filePath,
				name: 'file',
				formData,
				header,
				success:res=>{
					if(res.statusCode == 200){
						r(JSON.parse(res.data));
					}
				},
				fail: error => {
				}
			});
			Task.onProgressUpdate(function(res) {
				onProgressUpdate(res);
			});
			uploadTask(Task);
		}).then(res => {
			return {
				path:res.viewUrl
			}
		});
	}
}
export default Http